package cn.cxq.learning.string_matching;

/**
 * 暴力匹配
 */
public class ViolentMatch {

    private String matchingStr; //匹配的串
    private String matchedStr; //被匹配的串

    public ViolentMatch(String matchingStr, String matchedStr) {
        this.matchingStr = matchingStr;
        this.matchedStr = matchedStr;
    }

    /**
     * 搜索
     * @return 找到被匹配字符串在匹配字符串中首个字母对应的下标
     */
    public int search() {
        for (int i = 0; i < this.matchingStr.length(); i++) {
            int matchingIndex = i; // 被匹配的串的开始下标
            int matchedIndex; //匹配字符串的下标
            for (matchedIndex = 0; matchedIndex < this.matchedStr.length(); matchedIndex++) {
                if (matchingIndex == this.matchingStr.length()) {
                    break;
                }
                if (this.matchingStr.charAt(matchingIndex++) != this.matchedStr.charAt(matchedIndex)) {
                    break;
                }
            }
            if (matchedIndex == this.matchedStr.length()) {
                System.out.println("找到了，首字母下标是" + i + "~~~");
                return i;
            }
        }
        System.out.println("未找到匹配的串~~~");
        return -1;
    }
}
